package cn.buddha.jec.mvc.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName TongFilter
 * @Author 友野浩二
 * @Date 2020/4/9 15:15
 * @Description
 * @Version 1.0
 */
@WebFilter(filterName = "httpServletReplaceFilter", urlPatterns = "/*")
@Slf4j
public class TongFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 1-
//        if (request instanceof HttpServletRequest) {
//            // 防止流读取一次后就没有了, 所以需要将流继续写出去
//            ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(((HttpServletRequest) request));
//            // 在chain.doFiler方法中传递新的request、response对象
//            chain.doFilter(requestWrapper, response);
//        } else {
//            chain.doFilter(request, response);
//        }

        // 2-
        // 防止流读取一次后就没有了, 所以需要将流继续写出去
//        ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(((HttpServletRequest) request));
//        // 包装响应对象 resp 并缓存响应数据
//        ServletResponse responseWrapper = new TongResponseWrapper(((HttpServletResponse) response));
//        // 在chain.doFiler方法中传递新的request、response对象
//        chain.doFilter(requestWrapper, responseWrapper);

        // 3-
        // 防止流读取一次后就没有了, 所以需要将流继续写出去
//        BodyReaderHttpServletRequestWrapper requestWrapper = new BodyReaderHttpServletRequestWrapper(((HttpServletRequest) request));
//        // 在chain.doFiler方法中传递新的request、response对象
//        // 包装响应对象 resp 并缓存响应数据
//        TongResponseWrapper responseWrapper = new TongResponseWrapper(((HttpServletResponse) response));
//        chain.doFilter(requestWrapper, responseWrapper);
//
//        byte[] baos = responseWrapper.getBaos();
//        log.info("TongBaseRequest End, URI [{}]{}TongBaseResponse content is: {}",
//                requestWrapper.getRequestURI(),
//                System.lineSeparator(),
//                new String(baos, Charset.forName("UTF-8")));
//        // 将数据 再写到 response 中
//        response.getOutputStream().write(baos);

        // 对request、response进行一些预处理
        // 比如设置请求响应的编码
        request.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        // 业务逻辑编写
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
